package cn.com.wxd.servlet.wechat;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

import cn.com.wxd.wechat.common.exception.WxErrorException;
import cn.com.wxd.wechat.common.session.WxSessionManager;
import cn.com.wxd.wechat.common.util.StringUtils;
import cn.com.wxd.wechat.mass.api.WxMpConfigStorage;
import cn.com.wxd.wechat.mass.api.WxMpInMemoryConfigStorage;
import cn.com.wxd.wechat.mass.api.WxMpMessageHandler;
import cn.com.wxd.wechat.mass.api.WxMpMessageRouter;
import cn.com.wxd.wechat.mass.api.WxMpService;
import cn.com.wxd.wechat.mass.api.WxMpServiceImpl;
import cn.com.wxd.wechat.mass.bean.WxMpXmlMessage;
import cn.com.wxd.wechat.mass.bean.WxMpXmlOutMessage;
import cn.com.wxd.wechat.mass.bean.WxMpXmlOutTextMessage;

/**
 * Title:微信Servlet接口
 * Description:cn.com.wxd.servlet.wechat
 * 
 * Company: wxd网站系统
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-8-23 下午6:33:41
 *
 * @author WangXuDong
 * @version 1.0
 */
public class WechatServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1723885311232648128L;
	protected WxMpConfigStorage wxMpConfigStorage;
	protected WxMpService wxMpService;
	protected WxMpMessageRouter wxMpMessageRouter;
//	public void doGet(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		doPost(request,response);
//	}
//
//	public void doPost(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//
//		response.setContentType("text/html");
//		PrintWriter out = response.getWriter();
//		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
//		out.println("<HTML>");
//		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
//		out.println("  <BODY>");
//		out.print("    This is ");
//		out.print(this.getClass());
//		out.println(", using the POST method");
//		out.println("  </BODY>");
//		out.println("</HTML>");
//		out.flush();
//		out.close();
//	}

	public void init() throws ServletException {
		super.init();

		WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
		config.setAppId("wx663f8763860c8397"); // 设置微信公众号的appid
		config.setSecret("c8738d4acc851ce182c3adeef4df50e6"); // 设置微信公众号的app corpSecret
		config.setToken("wmwjia"); // 设置微信公众号的token
		config.setAesKey("uXw25er7O3fvfvjoTeotKfO2mcTewDWL9Hixsf0qpVb"); // 设置微信公众号的EncodingAESKey

		wxMpConfigStorage = config;  //设置账号等信息
		//WxMpServiceImpl wxService = new WxMpServiceImpl();
		//wxService.setWxMpConfigStorage(wxMpConfigStorage);

		// 用户的openid在下面地址获得 
		// https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=用户管理&form=获取关注者列表接口%20/user/get 
		//String openid = "...";
		//WxMpCustomMessage message = WxMpCustomMessage.TEXT().toUser(openid).content("Hello World").build();
		//wxService.customMessageSend(message);

		wxMpService = new WxMpServiceImpl();
		wxMpService.setWxMpConfigStorage(wxMpConfigStorage);

		WxMpMessageHandler handler = new WxMpMessageHandler() {
			@Override
			public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
					Map<String, Object> context, WxMpService wxMpService,
					WxSessionManager sessionManager) throws WxErrorException {
				WxMpXmlOutTextMessage m
				= WxMpXmlOutMessage.TEXT().content("测试加密消息").fromUser(wxMessage.getToUserName())
				.toUser(wxMessage.getFromUserName()).build();
				return m;
			}
		};
		wxMpMessageRouter = new WxMpMessageRouter(wxMpService);
		wxMpMessageRouter
		.rule()
		.async(true)
		.content("哈哈") // 拦截内容为“哈哈”的消息
		.handler(handler)
		.end();
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);

		String signature = request.getParameter("signature");
		String nonce = request.getParameter("nonce");
		String timestamp = request.getParameter("timestamp");
		if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
			// 消息签名不正确，说明不是公众平台发过来的消息
			response.getWriter().println("非法请求");
			return;
		}
		String echostr = request.getParameter("echostr");
		if (StringUtils.isNotBlank(echostr)) {
			// 说明是一个仅仅用来验证的请求，回显echostr
			response.getWriter().println(echostr);
			return;
		}

		String encryptType = StringUtils.isBlank(request.getParameter("encrypt_type")) ?
				"raw" :
					request.getParameter("encrypt_type");

		if ("raw".equals(encryptType)) {
			// 明文传输的消息
			//ServletInputStream sis = request.getInputStream();
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
			//System.out.println(IOUtils.toString(sis));
			//System.out.println("消息"+inMessage);
			WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
			
			response.getWriter().write(outMessage.toXml());
			//System.out.println("消息来了："+inMessage.getContent());
			return;
		}

		if ("aes".equals(encryptType)) {
			// 是aes加密的消息
			String msgSignature = request.getParameter("msg_signature");
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(request.getInputStream(), wxMpConfigStorage, timestamp, nonce, msgSignature);
			WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);
			response.getWriter().write(outMessage.toEncryptedXml(wxMpConfigStorage));
			System.out.println("消息来了："+inMessage.getContent());
			return;
		}

		response.getWriter().println("不可识别的加密类型");
		return;
	}

}
